<template>
  <div class="AddOrUpdate_main add_container">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio label="0">男</el-radio>
            <el-radio label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="账号" prop="userName">-->
        <!--          <el-input v-model="formData.userName" placeholder="请输入" clearable />-->
        <!--        </el-form-item>-->
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="formData.phonenumber" placeholder="请输入" clearable :disabled="id" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入" clearable />
        </el-form-item>
        <!--        <el-form-item label="角色" prop="roleIds">-->
        <!--          <el-input v-model="formData.roleIds" placeholder="请输入" clearable />-->
        <!--        </el-form-item>-->
        <el-form-item label="角色" prop="roleIds" class="full">
          <el-select v-model="formData.roleIds" filterable placeholder="请选择" multiple clearable>
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId" class="full">
          <el-select v-model="formData.deptId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="ID卡号" prop="idCard">
          <el-input v-model="formData.idCard" placeholder="请输入" clearable />
        </el-form-item> -->
        <el-form-item v-if="!id" label="密码" prop="password">
          <el-input v-model="formData.password" clearable :disabled="true" />
          <input type="password" hidden autocomplete="new-password">
          <div class="password_remark">初始密码默认为注册手机号后6位</div>
        </el-form-item>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import { addUser as save, updateUser as update, getUser as getById } from '@/api/system/user'
import { all as getRole } from '@/api/system/role'
import { all as getDept } from '@/api/system/dept'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {}
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      if (!value.trim()) {
        callback(new Error('手机号不能为空'))
      } else
      if (!reg.test(value.trim())) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validate_email = (rule, value, callback) => {
      if (value && value.trim()) {
        const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        if (!reg.test(value)) {
          callback(new Error('邮箱格式不正确'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      formData: {
        id: undefined,
        realName: undefined,
        sex: '0',
        userName: undefined,
        phonenumber: undefined,
        email: undefined,
        roleIds: undefined,
        deptId: undefined,
        idCard: undefined,
        password: ''
      },
      rules: {
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '账号不能为空', trigger: 'change' }
        ],
        phonenumber: [
          { required: true, validator: validatePhone, trigger: 'change' }
        ],
        email: [
          { validator: validate_email, trigger: 'change' }
        ]
        // password: [
        //   { required: true, message: '密码不能为空', trigger: 'change' }
        // ]
      },
      roleOptions: [],
      deptOptions: []
    }
  },
  watch: {
    'formData.phonenumber': function(newVal, oldVal) {
      const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/
      if (newVal.length == 11 & reg.test(newVal.trim())) {
        this.formData.password = newVal.substring(newVal.length - 6, newVal.length)
      } else {
        this.formData.password = ''
      }
    }
  },
  created() {
    this.initSelect()
    if (!this.id) { // 没有id就是新增
      Object.keys(this.defaultValue).forEach(key => { // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else { // 有id就是编辑
      this.getById()
    }
  },
  methods: {
    initSelect() {
      getRole({ status: 1 }).then(res => {
        this.roleOptions = res.data
      })
      getDept({ status: 1 }).then(res => {
        this.deptOptions = res.data
      })
    },
    getById() {
      getById(this.id).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.password = '******'
        this.formData.roleIds = res.roleIds
        // if (res.roles) {
        //   const cacheRoleIds = []
        //   res.roles.forEach(item => {
        //     cacheRoleIds.push(item.roleId + '')
        //   })
        //   this.formData.roleIds = cacheRoleIds
        // }
      })
    },
    onSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (!this.id) { // 没有id就是新增
            this.formData.userName = this.formData.phonenumber
            save(this.formData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              console.log(111111)
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList() // 调用父组件的刷新方法
              this.$parent.refreshs() // 调用父组件的刷新方法
            })
          } else { // 有id就是编辑
            this.formData.userId = this.id
            delete this.formData['password']
            update(this.formData).then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              this.$layer.close(this.layerid) // 关闭弹框
              this.$parent.getList()
            })
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .el-form-item__label{
  width: 70px !important;
}
/deep/ .el-form-item__content{
  width: 320px !important;
}
/deep/ .el-select__tags{
  max-width: 100% !important;
}
.password_remark{
  color: #999;
  font-size: 12px;
}
</style>
